using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UiCraftWindow : MonoBehaviour
{
    private TextMeshProUGUI itemName;
    private TextMeshProUGUI itemDescription;
    private Image itemIcon;
    private Image[] materialIcons;
    private Button craftButton;

    private void Awake()
    {
        itemName = transform.Find("ItemName").GetComponent<TextMeshProUGUI>();
        itemDescription = transform.Find("ItemDescription").GetComponent<TextMeshProUGUI>();
        itemIcon = transform.Find("ItemIcon").GetComponent<Image>();
        materialIcons = transform.Find("MaterialIcons").GetComponentsInChildren<Image>();
        craftButton = transform.Find("CraftButton").GetComponent<Button>();
        foreach (Image materialIcon in materialIcons)
        {
            materialIcon.color = Color.clear;
            TextMeshProUGUI materialAmount = materialIcon.GetComponentInChildren<TextMeshProUGUI>();
            materialAmount.text = string.Empty;
            materialAmount.color = Color.clear;
        }
    }

    public void Setup(ItemDataEquipment data)
    {
        if (!data) return;
        craftButton.onClick.RemoveAllListeners();
        itemName.text = data.ItemName;
        itemDescription.text = data.GetDescription();
        itemIcon.sprite = data.ItemIcon;
        foreach (Image materialIcon in materialIcons)
        {
            materialIcon.color = Color.clear;
            TextMeshProUGUI materialAmount = materialIcon.GetComponentInChildren<TextMeshProUGUI>();
            materialAmount.text = string.Empty;
            materialAmount.color = Color.clear;
        }

        for (int i = 0; i < data.craftingMaterials.Count; i++)
        {
            if (data.craftingMaterials.Count > materialIcons.Length) return;
            materialIcons[i].sprite = data.craftingMaterials[i].data.ItemIcon;
            materialIcons[i].color = Color.white;
            TextMeshProUGUI materialAmount = materialIcons[i].GetComponentInChildren<TextMeshProUGUI>();
            materialAmount.text = data.craftingMaterials[i].StackSize.ToString();
            materialAmount.color = Color.white;
        }

        craftButton.onClick.AddListener(() => Inventory.Instance.CanCraft(data, data.craftingMaterials));
    }
}